package org.example.ui;

import org.example.service.UserService;
import org.example.service.impl.UserServiceImpl;

import javax.swing.*;
import java.awt.*;
import java.net.URL;

public class LoginFrame extends JFrame {
    UserService userService = new UserServiceImpl();
    int loginCount = 0;

    public LoginFrame() {
        setUndecorated(true);
        setSize(980, 500);
        setLocationRelativeTo(null);

        // 关键修复1：设置内容窗格透明
        ((JComponent) getContentPane()).setOpaque(false);

        JLayeredPane layeredPane = getLayeredPane();
        layeredPane.setLayout(null);

        // 关键修复2：设置分层窗格透明
        layeredPane.setOpaque(false);

        // 公共 insets 设置（保持不变）
        Insets standardInsets = new Insets(5, 2, 10, 5);

        // 设置背景图片（增加加载失败处理）
        URL imgURL = LoginFrame.class.getClassLoader().getResource("background.jpeg");
        JLabel background = null;
        if (imgURL != null) {
            ImageIcon backgroundImage = new ImageIcon(imgURL);
            Image scaledImage = backgroundImage.getImage().getScaledInstance(
                    getWidth(), getHeight(), Image.SCALE_SMOOTH);
            background = new JLabel(new ImageIcon(scaledImage));
        } else {
            // 关键修复3：图片加载失败时使用纯色背景
            background = new JLabel();
            background.setOpaque(true);
            background.setBackground(new Color(100, 149, 237)); // 蓝色背景
            System.err.println("Couldn't find file: background.jpeg");
        }
        background.setBounds(0, 0, getWidth(), getHeight());
        layeredPane.add(background, new Integer(Integer.MIN_VALUE));

        // 创建登录表单面板
        JPanel loginPanel = new JPanel(new GridBagLayout());
        loginPanel.setOpaque(false); // 透明背景显示图片
        loginPanel.setBounds(120, -100, getWidth() + 150, getHeight() + 150); // 定位面板位置

        // 标题标签
        JLabel title = new JLabel("  欢迎登录", SwingConstants.CENTER);
        title.setFont(new Font("楷书", Font.BOLD, 45));
        title.setForeground(new Color(0, 190, 255)); // 紫色调
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 2;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = standardInsets;
        gbc.anchor = GridBagConstraints.CENTER;
        loginPanel.add(title, gbc);

        // 用户名标签
        JLabel usernameLabel = new JLabel("用户名：");
        usernameLabel.setFont(new Font("宋体", Font.PLAIN, 16));
        usernameLabel.setForeground(new Color(50, 50, 50));
        gbc = getNewGbc(standardInsets, 0, 1, GridBagConstraints.EAST);
        loginPanel.add(usernameLabel, gbc);

        // 用户名输入框
        gbc = getNewGbc(standardInsets, 1, 1, GridBagConstraints.WEST);
        JTextField txtUserName = new JTextField(10);
        txtUserName.setOpaque(false);
        txtUserName.setBackground(new Color(255, 255, 255, 180));
        loginPanel.add(txtUserName, gbc);

        // 密码标签
        JLabel passwordLabel = new JLabel("密码："); // 重命名变量避免重复
        passwordLabel.setFont(new Font("宋体", Font.PLAIN, 16));
        passwordLabel.setForeground(new Color(50, 50, 50));
        gbc = getNewGbc(standardInsets, 0, 2, GridBagConstraints.EAST);
        loginPanel.add(passwordLabel, gbc);

        // 密码输入框
        gbc = getNewGbc(standardInsets, 1, 2, GridBagConstraints.WEST);
        JPasswordField jPasswordField = new JPasswordField(10);
        jPasswordField.setOpaque(false);
        jPasswordField.setBackground(new Color(255, 255, 255, 180));
        loginPanel.add(jPasswordField, gbc);

        // 登录按钮
        JButton loginButton = new JButton("登录");
        loginButton.setBackground(new Color(70, 130, 180));
        loginButton.setForeground(Color.WHITE);
        loginButton.setOpaque(true);
        loginButton.setPreferredSize(new Dimension(60, 30));

        // 取消按钮
        JButton cancelButton = new JButton("取消");
        cancelButton.setBackground(new Color(70, 130, 180));
        cancelButton.setForeground(Color.WHITE);
        cancelButton.setOpaque(true);
        cancelButton.setPreferredSize(new Dimension(60, 30));

        // 创建按钮面板并使用GridBagLayout
        JPanel buttonPanel = new JPanel(new GridBagLayout());
        buttonPanel.setOpaque(false);

        // 设置登录按钮位置
        GridBagConstraints btnGbc = new GridBagConstraints();
        btnGbc.gridx = 0;
        btnGbc.gridy = 0;
        btnGbc.insets = new Insets(0, 0, 0, 20); // 右侧间距20px
        btnGbc.anchor = GridBagConstraints.CENTER;
        buttonPanel.add(loginButton, btnGbc);

        // 设置取消按钮位置
        btnGbc = new GridBagConstraints();
        btnGbc.gridx = 1;
        btnGbc.gridy = 0;
        btnGbc.anchor = GridBagConstraints.CENTER;
        buttonPanel.add(cancelButton, btnGbc);

        // 添加按钮面板到loginPanel
        gbc = getNewGbc(standardInsets, 0, 3, GridBagConstraints.CENTER);
        gbc.gridwidth = 2;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(1, 25, 0, 0); // 顶部间距30px
        loginPanel.add(buttonPanel, gbc);

        // 登录按钮事件
        loginButton.addActionListener(e -> {
            SwingUtilities.invokeLater(() -> {
                String userName = txtUserName.getText().trim();
                String password = new String(jPasswordField.getPassword());
                if (userName.isEmpty()) {
                    JOptionPane.showMessageDialog(LoginFrame.this, "用户名不能为空");
                    return;
                }
                if (password.isEmpty()) {
                    JOptionPane.showMessageDialog(LoginFrame.this, "密码不能为空");
                    return;
                }
                boolean login = userService.login(userName, password);
                if (login) {
                    new MainFrame();
                    dispose();
                } else {
                    loginCount++;
                    if (loginCount > 2) {
                        JOptionPane.showMessageDialog(LoginFrame.this,
                                "您已三次登录失败，程序将强制退出");
                        System.exit(1);
                    } else {
                        JOptionPane.showMessageDialog(LoginFrame.this,
                                "用户名或密码错误，登录失败");
                    }
                }
            });
        });

        // 取消按钮事件
        cancelButton.addActionListener(e -> System.exit(0));

        // 将登录面板添加到分层窗格的顶层
        layeredPane.add(loginPanel, new Integer(Integer.MAX_VALUE));

        setVisible(true);
    }

    // 辅助方法用于快速生成 GridBagConstraints
    private GridBagConstraints getNewGbc(Insets insets, int gridx, int gridy, int anchor) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = insets;
        gbc.gridx = gridx;
        gbc.gridy = gridy;
        gbc.anchor = anchor;
        return gbc;
    }
}